package com.zhehekeji.opsys.api.service.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhehekeji.opsys.api.code.LuckyAnswerResultCode;
import com.zhehekeji.opsys.api.common.util.DateFormatUtil;
import com.zhehekeji.opsys.api.conf.Config;
import com.zhehekeji.opsys.api.entity.TSurvey;
import com.zhehekeji.opsys.api.entity.TSurveyAnswer;
import com.zhehekeji.opsys.api.entity.TSurveyChoice;
import com.zhehekeji.opsys.api.entity.TSurveyQuestion;
import com.zhehekeji.opsys.api.req.LuckyAnswerReq;
import com.zhehekeji.opsys.api.resp.GetSurveyListResp;
import com.zhehekeji.opsys.api.resp.GetSurveyQuestionListResp;
import com.zhehekeji.opsys.api.resp.GetSurveyQuestionResp;
import com.zhehekeji.opsys.api.resp.GetSurveyResp;
import com.zhehekeji.opsys.api.resp.LuckyAnswerResp;
import com.zhehekeji.opsys.api.service.CommonService;
import com.zhehekeji.opsys.api.service.validate.LuckyAnswerValidate;
import com.zhehekeji.opsys.api.service.validate.ValidateRets;
import com.zhehekeji.opsys.api.service.validate.args.LuckyAnswerValidateArgs;

/**
 * @ClassName SurveyManagerService
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2016-11-11   下午1:44:37
 */
@Service
public class SurveyManagerService extends CommonService{
	
	private final static Logger logger = LoggerFactory.getLogger(SurveyManagerService.class);
	
	@Autowired
	private LuckyAnswerValidate luckyAnswerValidate;
	@Autowired
	private Config config;
	
	public GetSurveyResp getSurvey(String surveyCode) {
		GetSurveyResp resp = new GetSurveyResp();
		if (StringUtils.isBlank(surveyCode)){
			logger.error("问卷编码非法！");
			resp.setResultCode(LuckyAnswerResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc("问卷编码非法！");
			return resp;
		}
		try {
			TSurvey tmpTSurvey = entityDao.get(TSurvey.class, "code=?1", new Object[]{surveyCode});
			if (tmpTSurvey == null){
				logger.error("问卷不存在，问卷编码非法！");
				resp.setResultCode(LuckyAnswerResultCode.SURVEY_DOES_NOT_EXIST);
				resp.setResultDesc("问卷不存在，问卷编码非法！");
				return resp;
			}
			Integer tmpStatus = tmpTSurvey.getStatus();
			if (tmpStatus == 0){
				logger.error("问卷已经停用！");
				resp.setResultCode(LuckyAnswerResultCode.SURVEY_HAS_BEEN_STOPPED);
				resp.setResultDesc("问卷已经停用！");
				return resp;
			}
			resp.setCode(surveyCode);
			resp.setCpCode(tmpTSurvey.getCpCode());
			resp.setEndTime(DateFormatUtil.format(tmpTSurvey.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
			resp.setProfile(tmpTSurvey.getProfile());
			resp.setStartTime(DateFormatUtil.format(tmpTSurvey.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
			resp.setTitle(tmpTSurvey.getTitle());
			resp.setType(tmpTSurvey.getType());
			logger.info("获取问卷信息成功");
		} catch (Exception e) {
			logger.error("程序异常，" + e.getMessage(), e);
			resp.setResultCode(LuckyAnswerResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("程序异常");
		}
		return resp;
	}

	public GetSurveyListResp getSurveyList(long cpCode, int firstIndex, int maxResult) {
		GetSurveyListResp resp = new GetSurveyListResp();
		String tmpWhereJpql = null;
		if (cpCode != -1){
			tmpWhereJpql = "o.cpCode=" +cpCode + " and o.status=1";
		}else{
			tmpWhereJpql = "o.status=1";
		}
		try {
			String tmpCountHql = "select count(o.id) as count from TSurvey o where " + tmpWhereJpql;
			List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql, null, -1, -1);
			int tmpIntCount = 0;
			if (tmpListMapCount != null && !tmpListMapCount.isEmpty()){
				Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
				Long tmpLongCount = (Long) tmpMapCount.get("count");
				tmpIntCount = tmpLongCount.intValue();
			}
			if(tmpIntCount <= 0) return resp;
			 
			LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
			orderBy.put("createTime", "asc");
			List<TSurvey> tmpListTSurvey = entityDao.getScrollData(TSurvey.class, firstIndex, maxResult, tmpWhereJpql, null, orderBy);
			if (tmpListTSurvey == null || tmpListTSurvey.isEmpty()) return resp;
			List<GetSurveyListResp.SurveyInfo> tmpListSurveyInfo = new ArrayList<GetSurveyListResp.SurveyInfo>();
			GetSurveyListResp.SurveyInfo tmpSurveyInfo;
			for (TSurvey tmpTSurvey : tmpListTSurvey){
				tmpSurveyInfo = new GetSurveyListResp.SurveyInfo();
				tmpSurveyInfo.setCode(tmpTSurvey.getCode());
				tmpSurveyInfo.setCpCode(tmpTSurvey.getCpCode());
				tmpSurveyInfo.setEndTime(DateFormatUtil.format(tmpTSurvey.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
				tmpSurveyInfo.setProfile(tmpTSurvey.getProfile());
				tmpSurveyInfo.setStartTime(DateFormatUtil.format(tmpTSurvey.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
				tmpSurveyInfo.setTitle(tmpTSurvey.getTitle());
				tmpSurveyInfo.setType(tmpTSurvey.getType());
				
				tmpListSurveyInfo.add(tmpSurveyInfo);
			}
			resp.setSurveyInfos(tmpListSurveyInfo);
			resp.setRecordSize(tmpIntCount);
			logger.info("获取问卷列表成功");
		} catch (Exception e) {
			logger.error("获取问卷列表失败，程序异常，" + e.getMessage(), e);
			resp.setResultCode(LuckyAnswerResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("获取问卷列表失败，程序异常！");
		}
		return resp;
	}

	public GetSurveyQuestionListResp getSurveyQuestionList(String surveyCode, int firstIndex, int maxResult) {
		GetSurveyQuestionListResp resp = new GetSurveyQuestionListResp();
		if (StringUtils.isBlank(surveyCode)){
			logger.error("问卷编码非法！");
			resp.setResultCode(LuckyAnswerResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc("问卷编码非法！");
			return resp;
		}
		try {
			String tmpCountHql = "select count(o.id) as count from TSurveyQuestion o where o.tsurvey.code=? and o.status=1";
			List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataByHql(tmpCountHql, new Object[]{surveyCode}, -1, -1);
			int tmpIntCount = 0;
			if (tmpListMapCount != null && !tmpListMapCount.isEmpty()){
				Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
				Long tmpLongCount = (Long) tmpMapCount.get("count");
				tmpIntCount = tmpLongCount.intValue();
			}
			if(tmpIntCount <= 0) return resp;
			 
			LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
			orderBy.put("sequence", "desc");
			List<TSurveyQuestion> tmpListTSurveyQuestion = entityDao.getScrollData(TSurveyQuestion.class, firstIndex, maxResult, "o.tsurvey.code=?1 and o.status=1", new Object[]{surveyCode}, orderBy);
			if (tmpListTSurveyQuestion == null || tmpListTSurveyQuestion.isEmpty()) return resp;
			List<GetSurveyQuestionListResp.SurveyQuestionInfo> tmpListSurveyQuestionInfo = new ArrayList<GetSurveyQuestionListResp.SurveyQuestionInfo>();
			GetSurveyQuestionListResp.SurveyQuestionInfo tmpSurveyQuestionInfo;
			
			List<TSurveyChoice> tmpListTSurveyChoice;
			List<GetSurveyQuestionListResp.SurveyChoiceInfo> tmpListSurveyChoiceInfo;
			GetSurveyQuestionListResp.SurveyChoiceInfo tmpSurveyChoiceInfo;
			for (TSurveyQuestion tmpTSurveyQuestion : tmpListTSurveyQuestion){
				tmpSurveyQuestionInfo = new GetSurveyQuestionListResp.SurveyQuestionInfo();
				tmpSurveyQuestionInfo.setAnswer(tmpTSurveyQuestion.getAnswer());
				tmpSurveyQuestionInfo.setAnswerRequire(tmpTSurveyQuestion.getAnswerRequire());
				tmpSurveyQuestionInfo.setChangeDate(tmpTSurveyQuestion.getChangeDate());
				tmpSurveyQuestionInfo.setChoiceRequire(tmpTSurveyQuestion.getChoiceRequire());
				tmpSurveyQuestionInfo.setChoiceType(tmpTSurveyQuestion.getChoiceType());
				tmpSurveyQuestionInfo.setCpCode(tmpTSurveyQuestion.getCpCode());
				tmpSurveyQuestionInfo.setId(tmpTSurveyQuestion.getId());
				
				if (!StringUtils.isEmpty(tmpTSurveyQuestion.getPicture())){
					tmpSurveyQuestionInfo.setPicture(getHttpUrl(tmpTSurveyQuestion.getPicture()));
				}
				if (!StringUtils.isEmpty(tmpTSurveyQuestion.getPicturehd())){
					tmpSurveyQuestionInfo.setPicturehd(getHttpUrl(tmpTSurveyQuestion.getPicturehd()));
				}
				
				tmpSurveyQuestionInfo.setScore(tmpTSurveyQuestion.getScore());
				tmpSurveyQuestionInfo.setSequence(tmpTSurveyQuestion.getSequence());
				tmpSurveyQuestionInfo.setTitle(tmpTSurveyQuestion.getTitle());
				tmpSurveyQuestionInfo.setType(tmpTSurveyQuestion.getType());
				
				tmpListTSurveyChoice = entityDao.getScrollData(TSurveyChoice.class, -1, -1, "o.tsurveyQuestion.id=?1 and status=1", new Object[]{tmpTSurveyQuestion.getId()}, orderBy);
				if (tmpListTSurveyChoice != null && !tmpListTSurveyChoice.isEmpty()){
					tmpListSurveyChoiceInfo = new ArrayList<GetSurveyQuestionListResp.SurveyChoiceInfo>();
					for (TSurveyChoice tmpTSurveyChoice : tmpListTSurveyChoice){
						tmpSurveyChoiceInfo = new GetSurveyQuestionListResp.SurveyChoiceInfo();
						tmpSurveyChoiceInfo.setContent(tmpTSurveyChoice.getContent());
						tmpSurveyChoiceInfo.setCpCode(tmpTSurveyChoice.getCpCode());
						tmpSurveyChoiceInfo.setId(tmpTSurveyChoice.getId());
						tmpSurveyChoiceInfo.setOrderno(tmpTSurveyChoice.getOrderno());
						tmpSurveyChoiceInfo.setSequence(tmpTSurveyChoice.getSequence());
						tmpSurveyChoiceInfo.setType(tmpTSurveyChoice.getType());
						
						tmpListSurveyChoiceInfo.add(tmpSurveyChoiceInfo);
					}
					tmpSurveyQuestionInfo.setSurveyChoiceInfos(tmpListSurveyChoiceInfo);
				}
				
				tmpListSurveyQuestionInfo.add(tmpSurveyQuestionInfo);
			}
			resp.setSurveyQuestionInfos(tmpListSurveyQuestionInfo);
			resp.setRecordSize(tmpIntCount);
			logger.info("获取问题列表成功");
		} catch (Exception e) {
			logger.error("获取问题列表失败，程序异常，" + e.getMessage(), e);
			resp.setResultCode(LuckyAnswerResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("获取问题列表失败，程序异常！");
		}
		return resp;
	}

	@Transactional
	public LuckyAnswerResp luckyAnswer(LuckyAnswerReq luckyAnswerReq) {
		LuckyAnswerResp resp = new LuckyAnswerResp();
		Date currentDate = new Date();
		try{
			
			//验证有效性
			ValidateRets<TSurvey>  tmpValidateRets = luckyAnswerValidate.validate(new LuckyAnswerValidateArgs(resp, 
					luckyAnswerReq, currentDate));
			if (!tmpValidateRets.isSuccess()) return resp;
			TSurveyAnswer tmpTSurveyAnswer;
			TSurvey tmpTSurvey = tmpValidateRets.getEntity();
			List<LuckyAnswerReq.AnswerInfo> tmpListAnswerInfo = luckyAnswerReq.getAnswerInfos();
			long tmpQuestionId;
			TSurveyQuestion tmpTSurveyQuestion;
			
			LuckyAnswerResp.AnswerResultInfo tmpAnswerResultInfo;
			List<LuckyAnswerResp.AnswerResultInfo> tmpListAnswerResultInfo = new ArrayList<LuckyAnswerResp.AnswerResultInfo>();
			int tmpAnswerRequire;
			String tmpAnswer;
			for (LuckyAnswerReq.AnswerInfo tmpAnswerInfo : tmpListAnswerInfo){
				tmpQuestionId = tmpAnswerInfo.getQuestionId();
				tmpTSurveyQuestion = entityDao.get(TSurveyQuestion.class, tmpQuestionId);
				if (tmpTSurveyQuestion == null){
					logger.error(String.format("提交答案失败，参数非法，问题[%s]不存在！", tmpQuestionId));
					resp.setResultCode(LuckyAnswerResultCode.PARAMETER_IS_NOT_LEGAL);
					resp.setResultDesc(String.format("提交答案失败，参数非法，问题[%s]不存在！", tmpQuestionId));
					return resp;
				}
				tmpTSurveyAnswer = new TSurveyAnswer();
				tmpTSurveyAnswer.setChoiceIds(tmpAnswerInfo.getChoiceIds());
				tmpTSurveyAnswer.setChoiceOrdernos(tmpAnswerInfo.getChoiceOrdernos());
				tmpTSurveyAnswer.setCpCode(tmpTSurvey.getCpCode());
				tmpTSurveyAnswer.setCreateTime(currentDate);
				tmpTSurveyAnswer.setEpgPlatformType(luckyAnswerReq.getEpgPlatformType());
				tmpTSurveyAnswer.setProductCode(luckyAnswerReq.getProductCode());
				tmpTSurveyAnswer.setProductName(luckyAnswerReq.getProductName());
				tmpTSurveyAnswer.setResolution(luckyAnswerReq.getResolution());
				tmpTSurveyAnswer.setTsurveyQuestion(new TSurveyQuestion(tmpAnswerInfo.getQuestionId()));
				tmpTSurveyAnswer.setUserId(luckyAnswerReq.getUserID());
				entityDao.saveObj(tmpTSurveyAnswer);
				
				tmpAnswerRequire = tmpTSurveyQuestion.getAnswerRequire() == null ? 0 : tmpTSurveyQuestion.getAnswerRequire();
				tmpAnswer = tmpTSurveyQuestion.getAnswer();
				
				tmpAnswerResultInfo = new LuckyAnswerResp.AnswerResultInfo();
				tmpAnswerResultInfo.setQuestionId(tmpAnswerInfo.getQuestionId());
				tmpAnswerResultInfo.setAnswerRequire(tmpAnswerRequire);
				if (tmpAnswerRequire == 1){//有正确选项
					if (!StringUtils.isEmpty(tmpAnswer) && tmpAnswer.equals(tmpAnswerInfo.getChoiceIds())){
						//回答正确
						tmpAnswerResultInfo.setAnswerResult(1);
					}else{
						//回答错误
						tmpAnswerResultInfo.setAnswerResult(0);
					}
				}
				tmpListAnswerResultInfo.add(tmpAnswerResultInfo);
			}
			resp.setAnswerResultInfos(tmpListAnswerResultInfo);
			logger.info("提交答案成功");
		}catch(Exception e){
			logger.error("提交答案失败，程序异常！" , e);
			resp.setResultCode(LuckyAnswerResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("提交答案失败，程序异常！");
		}
		return resp;
	}

	public GetSurveyQuestionResp getCurrentSurveyQuestion(String surveyCode, String userID) {
		GetSurveyQuestionResp resp = new GetSurveyQuestionResp();
		if (StringUtils.isBlank(surveyCode)){
			logger.error("问卷编码非法！");
			resp.setResultCode(LuckyAnswerResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc("问卷编码非法！");
			return resp;
		}
		try {
			String tmpStrCurrentDay = DateFormatUtil.format(new Date(), "yyyy-MM-dd");
			TSurveyQuestion tmpTSurveyQuestion = entityDao.get(TSurveyQuestion.class, "o.tsurvey.code=?1 and o.changeDate=?2 and status=1", 
					new Object[]{surveyCode, tmpStrCurrentDay});
			if (tmpTSurveyQuestion == null){
				logger.error(String.format("日期[%s]的替换问题不存在", tmpStrCurrentDay));
				resp.setResultCode(LuckyAnswerResultCode.QUESTION_DOES_NOT_EXIST);
				resp.setResultDesc(String.format("日期[%s]的替换问题不存在", tmpStrCurrentDay));
				return resp;
			}
			LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
			orderBy.put("sequence", "desc");
			List<TSurveyChoice> tmpListTSurveyChoice = entityDao.getScrollData(TSurveyChoice.class, -1, -1, "o.tsurveyQuestion.id=?1 and status=1", new Object[]{tmpTSurveyQuestion.getId()}, orderBy);
			if (tmpListTSurveyChoice != null && !tmpListTSurveyChoice.isEmpty()){
				List<GetSurveyQuestionListResp.SurveyChoiceInfo> tmpListSurveyChoiceInfo = new ArrayList<GetSurveyQuestionListResp.SurveyChoiceInfo>();
				GetSurveyQuestionListResp.SurveyChoiceInfo tmpSurveyChoiceInfo;
				for (TSurveyChoice tmpTSurveyChoice : tmpListTSurveyChoice){
					tmpSurveyChoiceInfo = new GetSurveyQuestionListResp.SurveyChoiceInfo();
					tmpSurveyChoiceInfo.setContent(tmpTSurveyChoice.getContent());
					tmpSurveyChoiceInfo.setCpCode(tmpTSurveyChoice.getCpCode());
					tmpSurveyChoiceInfo.setId(tmpTSurveyChoice.getId());
					tmpSurveyChoiceInfo.setOrderno(tmpTSurveyChoice.getOrderno());
					tmpSurveyChoiceInfo.setSequence(tmpTSurveyChoice.getSequence());
					tmpSurveyChoiceInfo.setType(tmpTSurveyChoice.getType());
					
					tmpListSurveyChoiceInfo.add(tmpSurveyChoiceInfo);
				}
				resp.setSurveyChoiceInfos(tmpListSurveyChoiceInfo);
			}
			resp.setAnswer(tmpTSurveyQuestion.getAnswer());
			resp.setAnswerRequire(tmpTSurveyQuestion.getAnswerRequire());
			resp.setChangeDate(tmpTSurveyQuestion.getChangeDate());
			resp.setChoiceRequire(tmpTSurveyQuestion.getChoiceRequire());
			resp.setChoiceType(tmpTSurveyQuestion.getChoiceType());
			resp.setCpCode(tmpTSurveyQuestion.getCpCode());
			resp.setId(tmpTSurveyQuestion.getId());
			if (!StringUtils.isEmpty(tmpTSurveyQuestion.getPicture())){
				resp.setPicture(getHttpUrl(tmpTSurveyQuestion.getPicture()));
			}
			if (!StringUtils.isEmpty(tmpTSurveyQuestion.getPicturehd())){
				resp.setPicturehd(getHttpUrl(tmpTSurveyQuestion.getPicturehd()));
			}
			resp.setScore(tmpTSurveyQuestion.getScore());
			resp.setSequence(tmpTSurveyQuestion.getSequence());
			resp.setTitle(tmpTSurveyQuestion.getTitle());
			resp.setType(tmpTSurveyQuestion.getType());
			
			
			if (!StringUtils.isEmpty(userID)){
				LinkedHashMap<String, String> tmpOrderby = new LinkedHashMap<String, String>();
				tmpOrderby.put("createTime", "desc");
				String tmpWhereJpql = "date_format(o.createTime,'%Y-%m-%d') = '" + tmpStrCurrentDay + "' and o.tsurveyQuestion.id=?1 and o.userId=?2";
				List<TSurveyAnswer> tmpListTSurveyAnswer = entityDao.getScrollData(TSurveyAnswer.class, 0, 1, tmpWhereJpql, new Object[]{tmpTSurveyQuestion.getId(), userID}, tmpOrderby);
				if (tmpListTSurveyAnswer != null && !tmpListTSurveyAnswer.isEmpty()){
					TSurveyAnswer tmpTSurveyAnswer = tmpListTSurveyAnswer.get(0);
					String tmpQuestionAnswer = tmpTSurveyQuestion.getAnswer();
					String tmpUserAnswerChoiceIds = tmpTSurveyAnswer.getChoiceIds();
					resp.setUserAnswerMark(1);//已答题
					resp.setUserAnswerChoiceIds(tmpUserAnswerChoiceIds);
					resp.setUserAnswerChoiceOrdernos(tmpTSurveyAnswer.getChoiceOrdernos());
					if (!StringUtils.isEmpty(tmpQuestionAnswer)){
						if (StringUtils.isEmpty(tmpUserAnswerChoiceIds)){
							resp.setUserAnswerResult(0);//答题错误
						}else {
							if (tmpQuestionAnswer.equals(tmpUserAnswerChoiceIds)){
								resp.setUserAnswerResult(1);//答题正确
							}else{
								resp.setUserAnswerResult(0);//答题错误
							}
						}
					}
				}else{
					resp.setUserAnswerMark(0);//未答题
				}
			}
			logger.info(String.format("获取日期[%s]的替换问题成功", tmpStrCurrentDay));
		} catch (Exception e) {
			logger.error("程序异常，" + e.getMessage(), e);
			resp.setResultCode(LuckyAnswerResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("程序异常");
		}
		return resp;
	}
}

